﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using LimaLims.Application.Service.User.Dto;
using LimaLims.Core.Entity.System;
using Microsoft.EntityFrameworkCore;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LimaLims.Application.Service.Role
{
    /// <summary>
    /// 用户角色服务
    /// </summary>
    public class SysUserRoleService : ISysUserRoleService, ITransient
    {
        private readonly IRepository<SysUserRole> _sysUserRoleRep;  // 用户权限表仓储

        private readonly ISysRoleService _sysRoleService;

        public SysUserRoleService(IRepository<SysUserRole> sysUserRoleRep, ISysRoleService sysRoleService)
        {
            _sysUserRoleRep = sysUserRoleRep;
            _sysRoleService = sysRoleService;
        }

        public async Task DeleteUserRoleListByRoleId(long roleId)
        {
            var userRoles = await _sysUserRoleRep.Where(u => u.SysRoleId == roleId).ToListAsync();
            await _sysUserRoleRep.DeleteAsync(userRoles);
        }

        public async Task DeleteUserRoleListByUserId(long userId)
        {
            var surList = await _sysUserRoleRep.AsQueryable(m => m.SysUserId == userId, false).ToListAsync();
            await _sysUserRoleRep.DeleteAsync(surList);
        }

        public async Task<List<long>> GetUserRoleIdList(long userId, bool checkRoleStatus = true)
        {
            return await _sysUserRoleRep
            // 检查role状态，跳过全局tenantId&delete过滤器，超级管理员使用
                .Where(!checkRoleStatus, u => u.SysRole.ValidStatus, ignoreQueryFilters: true)
            // 当不是超级管理员的时候检查role状态和全局tenantId&delete过滤器
                .Where(checkRoleStatus, u => u.SysRole.ValidStatus)
                .Where(u => u.SysUserId == userId)
                .Select(u => u.SysRoleId)
                .ToListAsync();
        }

        /// <summary>
        /// 授权用户角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task GrantRole(UpdateUserRoleDataInput input)
        {

            var userRoles = await _sysUserRoleRep.Where(u => u.SysUserId == input.Id).ToListAsync();
            await _sysUserRoleRep.DeleteAsync(userRoles);
            if (input.GrantRoleIdList != null && input.GrantRoleIdList.Count > 0)
            {
                var roles = input.GrantRoleIdList.Select(u => new SysUserRole
                {
                    SysUserId = input.Id,
                    SysRoleId = u
                }).ToList();
                await _sysUserRoleRep.InsertAsync(roles);
            }
        }
    }
}
